package com.example.cardgameapp

import android.os.Bundle
import android.content.Intent
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat

class CardGameActivity : AppCompatActivity() {
    private lateinit var gridLayout: GridLayout
    private lateinit var scoreTextView: TextView
    private var game: CardMatchingGame? = null
    private var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)

        gridLayout = findViewById(R.id.grid_cards)
        scoreTextView = findViewById(R.id.tv_score)
        game = CardMatchingGame(8)
        updateUI()

        findViewById<Button>(R.id.btn_reset_game).setOnClickListener {
            game = CardMatchingGame(8)
            score = 0
            scoreTextView.text = getString(R.string.label_score) + " $score"
            updateUI()
        }

        findViewById<Button>(R.id.btn_exit).setOnClickListener {
            val resultIntent = Intent().apply {
                putExtra("highestScore", score)
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }
    }

    private fun updateUI() {
        gridLayout.removeAllViews()
        val cards = game?.cards ?: return
        val columnCount = gridLayout.columnCount

        for (i in cards.indices) {
            val card = cards[i]
            val button = Button(this).apply {
                // 卡片正面：加载小写命名的图案（如card_a.jpg）
                val cardDrawable: Drawable? = try {
                    ResourcesCompat.getDrawable(resources, resources.getIdentifier("card_${card.content.lowercase()}", "drawable", packageName), theme)
                } catch (e: Exception) {
                    null
                }
                // 卡片背面：加载huangyuan.jpg
                val backDrawable = ResourcesCompat.getDrawable(resources, R.drawable.daily, theme)

                background = if (card.isFaceUp) {
                    cardDrawable ?: backDrawable
                } else {
                    backDrawable
                }
                text = if (card.isFaceUp) card.content else ""
                setOnClickListener {
                    game?.chooseCard(card)
                    score = game?.score ?: 0
                    scoreTextView.text = getString(R.string.label_score) + " $score"
                    updateUI()
                }
                layoutParams = GridLayout.LayoutParams().apply {
                    width = 0
                    height = 0
                    columnSpec = GridLayout.spec(i % columnCount, 1f)
                    rowSpec = GridLayout.spec(i / columnCount, 1f)
                    setMargins(4, 4, 4, 4)
                }
            }
            gridLayout.addView(button)
        }
    }
}

// 卡片数据类和游戏逻辑类保持不变（注意content为"A"-"H"，与小写文件名通过lowercase()转换匹配）
data class Card(
    val content: String,
    var isFaceUp: Boolean = false,
    var isMatched: Boolean = false
)

class CardMatchingGame(private val pairCount: Int) {
    val cards: List<Card>
    var score = 0
    init {
        val contents = listOf("A", "B", "C", "D", "E", "F", "G", "H")
            .flatMap { listOf(it, it) }
            .shuffled()
        cards = contents.map { Card(it) }
    }
    fun chooseCard(card: Card) {
        if (card.isFaceUp || card.isMatched) return

        val faceUpCards = cards.filter { it.isFaceUp && !it.isMatched }
        card.isFaceUp = true

        when (faceUpCards.size) {
            0 -> return
            1 -> {
                val otherCard = faceUpCards[0]
                if (card.content == otherCard.content) {
                    card.isMatched = true
                    otherCard.isMatched = true
                    score += 10
                } else {
                    score -= 1
                }
            }
            else -> {
                faceUpCards.forEach { it.isFaceUp = false }
            }
        }
    }
}